﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Sockets;
using System.Net;
using System.Threading;

using Server.Functions;
using Server.Account;

namespace Server.Comm
{
    public delegate void ConnectedHandler(CommObj commObj);

    public sealed class CommMgr : Singleton<CommMgr>
    {
        //event
        public event ConnectedHandler OnConnected;

        static ManualResetEvent s_allDone = new ManualResetEvent(false);
        Socket m_listener = null;

        public CommMgr()
        {
        }

        public void StartListening()
        {
            m_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(CommConfig.HOST), CommConfig.PORT);

            try
            {
                m_listener.Bind(localEndPoint);
                m_listener.Listen(200);
                while (true)
                {
                    s_allDone.Reset();

                    m_listener.BeginAccept(new AsyncCallback(AcceptCallback), m_listener);
                    s_allDone.WaitOne();
                }
            }
            catch (System.Exception)
            {
                m_listener.Close();
            }
        }

        private static void AcceptCallback(IAsyncResult ar)
        {
            s_allDone.Set();

            Socket listener = (Socket)ar.AsyncState;
            Socket handler = (Socket)listener.EndAccept(ar);

            CommObj commObj = new CommObj(handler);
            if (CommMgr.GetInstance().OnConnected != null)
            {
                CommMgr.GetInstance().OnConnected(commObj);
            }
        }
    }
}
